package zhr.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import zhr.store.common.BaseContext;
import zhr.store.common.Result;
import zhr.store.controller.DishController;
import zhr.store.domain.*;
import zhr.store.service.*;
import zhr.store.mapper.OrdersMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
* @author 詹华榕
* @description 针对表【orders(订单表)】的数据库操作Service实现
* @createDate 2023-04-17 15:11:59
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService detailService;
    @Autowired
    private DishService dishService;
    @Autowired
    private DishController dishController;
    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public Result<String> submit(Orders orders){
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        //获取购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if (list == null) {
            throw new ClassCastException("购物车为空");
        }
        //生成订单
        long id = IdWorker.getId();
        //计算金额
        AtomicInteger amount = new AtomicInteger(0);
        //订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            //查询商品库存
            Long dishId = shoppingCart.getDishId();
            Dish dish = dishService.getById(dishId);
            //获取购买数量
            Integer number = shoppingCart.getNumber();
            //判断商品库存
            if(dish.getInventory()<number){
                return Result.error("库存不足");
            }
            //扣减商品库存,增加销量
            dish.setInventory(dish.getInventory()-number);
            dish.setSale(dish.getSale()+number);
            dishController.updateInventory(dish);
            //修改状态
            if (dish.getInventory()-number < 1){
                dishController.banDish(new Long[]{dishId});
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setAmount(shoppingCart.getAmount());
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        //查询用户
        User user = userService.getById(userId);
        //查询地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //新增订单表
        orders.setId(id);
        orders.setStatus(2);
        orders.setUserId(user.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setPhone(user.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        save(orders);
        //新增订单明细表
        detailService.saveBatch(orderDetails);
        //清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        return Result.success("下单成功");
    }

}




